package com.river.boot.biz.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.river.boot.biz.converter.ProductSpecConverter;
import com.river.boot.biz.mapper.ProductSpecMapper;
import com.river.boot.biz.model.entity.ProductSpec;
import com.river.boot.biz.model.entity.ProductSpecOption;
import com.river.boot.biz.model.form.ProductSpecForm;
import com.river.boot.biz.model.form.ProductSpecOptionForm;
import com.river.boot.biz.model.query.ProductSpecQuery;
import com.river.boot.biz.model.vo.ProductSpecVO;
import com.river.boot.biz.service.ProductSpecService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜品规格服务实现类
 *
 * @author JiangCheng Xiang
 * @since 2025-04-25 15:49
 */
@Service
@RequiredArgsConstructor
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec> implements ProductSpecService {

    private final ProductSpecConverter productSpecConverter;
    private final ProductSpecOptionServiceImpl productSpecOptionService;

    /**
     * 获取菜品规格分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<ProductSpecVO>} 菜品规格分页列表
     */
    @Override
    public IPage<ProductSpecVO> getProductSpecPage(ProductSpecQuery queryParams) {
        Page<ProductSpecVO> pageVO = this.baseMapper.getProductSpecPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取菜品规格表单数据
     *
     * @param id 菜品规格ID
     * @return
     */
    @Override
    public ProductSpecForm getProductSpecFormData(Long id) {
        ProductSpec entity = this.getById(id);
        return productSpecConverter.toForm(entity);
    }

    /**
     * 新增菜品规格
     *
     * @param formData 菜品规格表单对象
     * @return
     */
    @Override
    public boolean saveProductSpec(ProductSpecForm formData) {
        ProductSpec entity = productSpecConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新菜品规格
     *
     * @param id       菜品规格ID
     * @param formData 菜品规格表单对象
     * @return
     */
    @Override
    public boolean updateProductSpec(Long id, ProductSpecForm formData) {
        ProductSpec entity = productSpecConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除菜品规格
     *
     * @param ids 菜品规格ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteProductSpecs(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的菜品规格数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Transactional
    @Override
    public void batchSaveProductSpec(Long productId, List<ProductSpecForm> specifications) {
        // 删除原有的菜品规格
        this.productSpecOptionService.deleteProductSpecOptionsByProductId(productId);
        this.lambdaUpdate().eq(ProductSpec::getProductId, productId).remove();

        // 保存菜品规格
        specifications.forEach(spec -> {
            spec.setId(null);
            spec.setProductId(productId);
        });
        List<ProductSpec> productSpecs = productSpecConverter.toEntityList(specifications);
        this.saveBatch(productSpecs);

        // 保存菜品规格选项
        productSpecs.forEach(spec -> {
            List<ProductSpecOption> specOptions = spec.getSpecOptions();
            specOptions.forEach(option -> {
                option.setId(null);
                option.setSpecId(spec.getId());
            });
            productSpecOptionService.saveBatch(specOptions);
        });
    }

    @Override
    public List<ProductSpecForm> getProductSpecsByProductId(Long productId) {
        List<ProductSpec> productSpecs = this.lambdaQuery().eq(ProductSpec::getProductId, productId).list();
        List<ProductSpecForm> specFormList = productSpecConverter.toFormList(productSpecs);

        // 填充菜品规格选项
        List<ProductSpecOptionForm> productSpecOptions = productSpecOptionService.getProductSpecOptionsByProductId(productId);

        Map<Long, List<ProductSpecOptionForm>> productSpecOptionMap = productSpecOptions.stream().collect(Collectors.groupingBy(ProductSpecOptionForm::getSpecId));
        specFormList.forEach(specForm -> {
            specForm.setSpecOptions(productSpecOptionMap.get(specForm.getId()));
        });

        return specFormList;
    }

}
